# author： Zichen
# date: 2021-02-03

import check_ip  # 检查ip模块
import qmsgsent  # Qmsg酱信息推送模块
import qqmailsent01  # QQ邮箱信息推送模块
import baidu_translate  # 百度翻译模块
from os import system as os_system  # cmd命令执行模块
from os.path import exists as path_exists
from time import sleep  # 程序休眠模块
from sys import platform  # 识别操作系统模块
import rsa_encryption  # 加密模块
import crawler_weather  # 天气模块
import bilibili_public  # 获得某主播直播状态模块
import bilibili_private  # 使用cookie直接获取自己订阅的主播当前的直播状况模块
import epic_freegame  # 获取epic免费游戏模块
from rich.console import Console  # 控制台模块

# 程序文本规则：
# debug文本：绿色
# error文本：红色
# 提示文本：蓝色
# 目标信息反馈文本：橙色 #ffb74d
# 程序菜单标题及提示文本中需特殊强调部分： 青色 #63e6be
orange = '#ffb74d'
cyan = '#63e6be'
grey = '#bdbdbd'
# 待定颜色：；灰色 #bdbdbd
console = Console(color_system="auto")  # 创建控制台
console.print(
    "[green]Microsoft Windows [版本 %s]" % platform)
check_ip.Check_IP({'120.241.25.80': 'smtp.qq.com (QQ邮箱)',  # QQ邮箱
                   '220.181.136.120': 'sc.ftqq.com (Qmsg酱)',  # Qmsg酱
                   '103.48.169.235': 'www.7meiju.com (美剧网站)',  # 美剧网站
                   '36.152.44.216': 'fanyi.baidu.com (百度翻译)',  # 百度翻译
                   '223.111.212.163': 'www.weather.com.cn (中国天气网)',  # 中国天气网
                   '119.28.36.78': 'www.epicgames.com (EPIC商店)',  # EPIC商店
                   }
                  )  # 调用检查模块检查ip
console.rule("[bold #ffb74d]Welcome")

While = 1
while While >= 1:
    command = console.input('[bold blue]>>>')
    console.print("[bold green]Analyzing your command...[/bold green]")
    sleep(0.5)
    if command == '/exit':  # 退出指令
        console.print(
            "ｂ（￣▽￣）ｄ[bold purple]Thanks for using![/bold purple]")
        sleep(3)  # 输入退出命令后延迟3秒执行
        break
    elif command == '/help':
        if path_exists('./About/main.html') == True:
            console.print(
                '[bold %s]帮助文档路径为./About/main.html，请自主打开查看QAQ' % orange)
        else:
            console.print(
                '[bold red]未找到帮助文件！！！请检查帮助文件是否路径是否为[/bold red][%s]./About/main.html' % cyan)
    elif command == '/qmail':  # QQ邮箱推送模块
        console.print(
            "[bold blue]Please enter fromaddr, password, toaddrs, message and message_subject[/bold blue]")
        fromaddrs = console.input('[bold blue]Fromaddrs(邮件发送方邮箱地址):')
        try:  # 有多个地址就分割，没有就不分割
            toaddrs = console.input(
                '[bold blue]Toaddrs (邮件接受方邮箱地址，注意需要多个邮件地址用,隔开，这意味着你可以写多个邮件地址群发):').split(',')
        except:
            toaddrs = [console.input(
                '[bold blue]Toaddrs (邮件接受方邮箱地址，注意需要多个邮件地址用,隔开，这意味着你可以写多个邮件地址群发):')]
        password = console.input('[bold blue]Password(授权码):')
        message_subject = console.input('[bold blue]Message_subject(邮件主题):')
        message = console.input('[bold blue]Message(邮件内容):')
        while While >= 1:
            isAppendix = console.input('[bold blue]是否发送附件？(Y/F)\n<<<')
            if isAppendix.upper() == 'Y':  # 将输入的字符全部转换为大写字母
                fileName = console.input('[blue]FileName(附件文件名.带后缀):')
                filePath = console.input('[blue]FilePath(附件绝对路径):')
                try:
                    qqmailsent01.sent(fromaddrs, toaddrs, password,
                                      message_subject, message, fileName, filePath)
                    break
                except:
                    console.print_exception()
                    break
            elif isAppendix.upper() == 'F':
                try:
                    qqmailsent01.sent(fromaddrs, toaddrs, password,
                                      message_subject, message, None, None)
                    break
                except:
                    console.print_exception()
                    break
            else:
                console.print(
                    "[bold red][Qmail]Please enter again[/bold red]\n")
    elif command == '/qmsg':  # Qmsg推送模块
        console.print(
            "[bold blue]Please enter key and message[/bold blue]")
        key = console.input('[bold blue]YourKey:')
        message = console.input('[bold blue]Message:')
        try:
            qmsgsent.sent(key, message)
        except:
            console.print_exception()
    elif command == '/bdtran':  # 调用百度翻译api
        baidu_translate.main_handler(1, 2)
    elif command == '/ping':  # ping其他地址
        IP = console.input('[bold blue]IP or Domain name(IP地址或域名):')
        try:
            os_system('ping %s' % IP)
        except:
            console.print_exception()
    elif command == '/rsa':  # rsa加密模块
        while While >= 1:
            command_rsa = console.input(
                '\n[bold %s]{rsa模块功能菜单}[/bold %s]\n\
[bold blue]/ck 创建公钥、私钥\n\
/encrypt 公钥加密\n\
/decrypt 私钥解密\n\
/exit 退出rsa模块\n\
<<<[/bold blue]' % (cyan, cyan))
            if command_rsa == '/ck':
                key_name = console.input(
                    '[bold blue]Please enter the name of the [/bold blue][bold #63e6be]public and private key[/bold #63e6be][bold blue] to create.\n<<<[/bold blue]')
                rsa_encryption.create_keys(key_name)
            elif command_rsa == '/encrypt':  # 用公钥加密
                text = console.input(
                    '[blue]Please enter the text to be encrypted\n<<<')
                key_name = console.input(
                    '[bold blue]Please enter the path of the [/bold blue][bold #63e6be]public key.[/bold #63e6be][bold blue]\n<<<[/bold blue]')
                rsa_encryption.Public_key_encryption(text, key_name)
            elif command_rsa == '/decrypt':  # 私钥解密
                crypt_text = console.input(
                    '[bold blue]Please enter the [/bold blue][bold #63e6be]Encrypted[/bold #63e6be][bold blue] text`s Path to be decrypted\n<<<[/bold blue]')
                key_path = console.input(
                    '[bold blue]Please enter the path of the [/bold blue][bold #63e6be]private key.[/bold #63e6be][bold blue]\n<<<[/bold blue]')
                rsa_encryption.Private_key_decryption(
                    crypt_text, key_path)
            elif command_rsa == '/exit':
                console.print(
                    '[red]The RSA module has been exited\n已退出rsa模块\n')
                break
            else:
                console.print(
                    "[bold red][rsa]Please enter again[/bold red]")
    elif command == '/weather':  # 获取天气
        Day = console.input(
            '[bold blue]Please enter the number of days to query.\n请输入要查询的天数\n<<<')
        crawler_weather.main(int(Day))
    elif command == '/bililive':
        while While >= 1:
            bili_command = console.input(
                '\n[bold %s]{BilibiliLive模块}[/bold %s]\n\
[bold blue]/txt 通过txt文件读取需查询的主播的uid \n\
/uid 通过输入uid查询\n\
/pri 通过cookie查询自己订阅的主播的开播情况\n\
(Tip:输入/exit 退出模块)\n\
<<<[/bold blue]' % (cyan, cyan))
            if bili_command == '/txt':
                try:
                    with open(r'./bilibililive_data.txt', 'r', encoding='utf-8') as f:
                        for i in f.readlines():
                            uid = i.split(':')[1].replace('\n', '')
                            Data = bilibili_public.GetData(uid)
                            Livedata = bilibili_public.GetLivedata(Data)
                            Live_title = bilibili_public.GetLive_title(
                                Livedata)
                            Live_url = bilibili_public.GetLive_url(Livedata)
                            LiveStatus = bilibili_public.GetLiveStatus(
                                Livedata)
                            Name = bilibili_public.GetName_Mid(Data)[0]
                            UID = bilibili_public.GetName_Mid(Data)[1]
                            console.print("{orange} [BiliBiliLive]\n\
主播：{name} UID:{uid}\n\
{title}  直播间链接:{url}\n\
当前直播状态：{Status}{orange_end}\n\
                        ".format(
                                orange='[%s]' % orange, orange_end='[/%s]' % orange,
                                name=Name, uid=UID,
                                url=Live_url, title=Live_title,
                                Status=LiveStatus
                            ))
                except:
                    console.print_exception()
            elif bili_command == '/uid':
                while While >= 1:
                    uid = console.input(
                        '[bold blue]UID (Tip:输入/exit 退出模块)<<<')
                    if uid != '/exit':
                        Data = bilibili_public.GetData(uid)
                        Livedata = bilibili_public.GetLivedata(Data)
                        Live_title = bilibili_public.GetLive_title(Livedata)
                        Live_url = bilibili_public.GetLive_url(Livedata)
                        LiveStatus = bilibili_public.GetLiveStatus(Livedata)
                        Name = bilibili_public.GetName_Mid(Data)[0]
                        UID = bilibili_public.GetName_Mid(Data)[1]
                        console.print("{orange} [BiliBiliLive]\n\
主播：{name} UID:{uid}\n\
{title}  直播间链接:{url}\n\
当前直播状态：{Status}{orange_end}\n\
                        ".format(
                            orange='[%s]' % orange, orange_end='[/%s]' % orange,
                            name=Name, uid=UID,
                            url=Live_url, title=Live_title,
                            Status=LiveStatus
                        ))
                    else:
                        break
            elif bili_command == '/pri':
                cookie = console.input('[blue]Please enter your cookie:\n<<<')
                if bilibili_private.GetData(cookie) == None:
                    console.print('[%s]\n目前没有主播开播！\n' % orange)
                else:
                    try:
                        for i in bilibili_private.GetData(cookie):
                            console.print("{orange} [BiliBiliLive]\n\
主播：{name} UID:{uid}\n\
{title}  直播间链接:{url}\n{orange_end}".format(
                                orange='[%s]' % orange, orange_end='[/%s]' % orange,
                                name='[#63e6be]%s[/#63e6be]' % i.get('uname'), uid='[#63e6be]%s[/#63e6be]' % i.get('uid'),
                                url=i.get('link'), title=i.get('title')
                            ))
                    except:
                        console.print_exception()
            elif bili_command == '/exit':
                console.print(
                    '[red]The bililive module has been exited\n已退出bililive模块\n')
                break
            else:
                console.print(
                    "[bold red][bililive]Please enter again[/bold red]\n")
    elif command == '/epic_fg':  # 获取epic免费游戏模块
        Data = epic_freegame.GetData()
        console.print('[%s]\n{Epic免费游戏}' % cyan)
        for i in Data:
            try:
                endDate_lst = i.get('promotions').get('promotionalOffers')[0].get(
                    'promotionalOffers')[0].get('endDate').split('T')
                endDate = endDate_lst[0]+' '+endDate_lst[1].split('.')[0]
            except:
                endDate = 'None'
            console.print('[%s]  %s  【截止日期】%s' %
                          (orange, i.get('title'), endDate))
    else:
        console.print(
            "[bold red]Please enter again[/bold red]\n[bold blue]Tip:You can type /help for help[/bold blue]")
